package servlets;

/*
 * Created By: Andrew Perdec
 * Sheridan ID: 991 351 681
 * Date Created: Sep 16, 2014
 * Version: 1.0
 * Email: aperdec@gmail.com
 */
import assignment3.Account;
import assignment3.OneWayHash;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Owner
 */
public class RegisterServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {

            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("Driver loaded okay");
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/pegasus_library_database", "root", "starwars");
            System.out.println("Connection okay");
            Statement statement = connection.createStatement();
            System.out.println("Statement okay");

            String username = request.getParameter("uid");
            String password = request.getParameter("pwd");
            String password2 = request.getParameter("pwd2");
            String email = request.getParameter("email");
            String admin = request.getParameter("admin");

            System.out.println(admin);
            
            if (password.equals(password2)) {
                ResultSet rs = statement.executeQuery("SELECT * FROM  `users` WHERE  `username` LIKE  '" + username + "'");
                if (rs.next()) {
                    request.setAttribute("errorMessageRegistration", "Username already taken");
                    RequestDispatcher rd = request.getRequestDispatcher("register.jsp");
                    rd.forward(request, response);
                } else {
                    Account account;
                    if (admin != null) {
                        String hashPassword = OneWayHash.hash(password);
                        statement.execute("INSERT INTO users values ('" + username + "', '" + hashPassword + "', '" + email + "', 'admin')");
                        account = new Account(username, password, email, "admin");
                    } else {
                        String hashPassword = OneWayHash.hash(password);
                        statement.execute("INSERT INTO users values ('" + username + "', '" + hashPassword + "', '" + email + "', 'guest')");
                        account = new Account(username, password, email, "guest");
                    }
                    
                    HttpSession hs = request.getSession();
                    hs.setAttribute("account", account);
                    hs.setAttribute("loggedIn", true);
                    RequestDispatcher rd = request.getRequestDispatcher("account");
                    rd.forward(request, response);
                }
            } else {
                request.setAttribute("errorMessageRegistration", " <script> window.onload = function() {alert(\"Passwords did not match!\");}</script>");
                RequestDispatcher rd = request.getRequestDispatcher("register.jsp");
                rd.forward(request, response);
            }
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(RegisterServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(RegisterServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
